package com.ddf.zero.controller;

import com.ddf.publics.config.Utill;
import com.ddf.publics.entity.*;
import com.ddf.publics.service.*;
import com.ddf.publics.tool.Constant;
import com.ddf.publics.tool.MoneyFund;
import com.ddf.publics.utils.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import java.security.Principal;
import java.util.*;

/**
 * Created by Zero on 2020-6-9 14:46
 */
@Controller
public class LoanHistoryController {
    @Autowired
    private LoginService loginService;

    @Autowired
    private LoanApplicationService loanApplicationService;

    @Autowired
    private UserInfoService userInfoService;

    @Autowired
    private ZeroService zeroService;

    @Autowired
    private RepaymentService repaymentService;

    @Autowired
    private RedisUtil redisUtil;

    @Autowired
    private UserService userService;

    //资金记录
    @Resource
    private FundService fundService;

    @Autowired
    private PayPwdService payPwdService;

    @Autowired
    private DueService dueService;


    @ResponseBody
    @RequestMapping("/loanList")
    public List<LoanVo> LoanHistoryList(Principal principal,Integer page,Integer limit,Integer count){
        User user = loginService.queryByPhone(principal.getName());
        if (page == null){
            page =1;
        }
        if (limit == null){
            limit =5;
        }
        if (count == null){
            count =zeroService.LoanCount(user.getId());
        }
        Page pages = new Page();
        pages.setAllCount(count);
        pages.setCount(limit);
        pages.setPage(page);
        //查询用户所有的借贷
        List<LoanApplication> loanApplications = zeroService.queryAllByLimitUserId(user.getId(),pages.getLimit(),pages.getCount());
        //借贷所有的所有信息
        ArrayList<LoanVo> ls = new ArrayList<>();
        loanApplications.forEach((loanApplication)->{
            //查询出单个借贷信息
            LoanVo loanVo = zeroService.UserLoan(loanApplication.getLId());
            loanData(loanVo);
            ls.add(loanVo);
        });
        return ls;
    }
    //去用户借贷页面
    @RequestMapping("/loanHistory")
    public String LoanHistoryController(Principal principal, Model model){
        User user = loginService.queryByPhone(principal.getName());
        Integer count = zeroService.LoanCount(user.getId());
        model.addAttribute("lscount",count);
        return "/userInfo/loanHistory";
    }

    @RequestMapping("/loanHistory/{lid}")
    public String LoanHistory(@PathVariable int lid, Model model){
        //查询出单个借贷信息
        LoanVo loanVo = zeroService.UserLoan(lid);
        //LoanVo loanVo = loanVos.get(loanVos.size() - 1);
        loanData(loanVo);
        //下期还款剩余时间
        model.addAttribute("term",null);
        //记录还款时间
        for (int i = 1; i <=loanVo.getL_month() ; i++) {
            long expire = redisUtil.getExpire("loan:" + loanVo.getL_id() + "," + i);
            if(expire!=-2){
                int dueDay = (int) Math.ceil(expire / 60 / 60 / 24);
                Calendar calendar = new GregorianCalendar();  // 定义calendar对象
                calendar.setTime(new Date()); // 把当前系统时间赋值给calendar
                calendar.add(calendar.DATE,dueDay); // 在日期中增加天数
                Date date = calendar.getTime(); // 把calendar转换回日期格式
                model.addAttribute("term",date);
                model.addAttribute("qishu",i);
                break;
            }
            model.addAttribute("qishu",i);
        }
        model.addAttribute("ls",loanVo);
        return "/userInfo/loandetails";
    }

    //确认借贷订单
    @PostMapping("/confirm")
    @ResponseBody
    public String confirm(int lid,boolean flag,String pwd){
        LoanApplication loan = new LoanApplication();
        loan.setLId(lid);
        //用户确定
        if (flag){//改为已放款
            loan.setOrderState(Constant.LOAN_ORDER_STATE_LOAN_ING);
        }else {//用户取消
            loan.setOrderState(Constant.NLOAN_ORDER_STATE_CACEL);
        }
        loanApplicationService.update(loan);
        return "";
    }

    @RequestMapping("/repayment")
    @ResponseBody
    public String repayment(Principal principal,Repayment repayment,String paypwd){
        User user = loginService.queryByPhone(principal.getName());
        int userId = user.getId();
        //密码校验
        switch (payPwdService.payPwd(userId, paypwd)){
            case Constant.PAY_LOCK:
                return "2";
            case Constant.PAY_NO:
                return "1";
        }
        UserInfo userInfo=userInfoService.userInfoList(userId);
        //扣除用户余额
        Float money = userInfo.getMoney();
        Float balance = money - repayment.getRMoney();
        //用户余额不足
        if(balance<0){
            return "3";
        }
        userInfo.setMoney(balance);
        //扣除余额
        userInfoService.update(userInfo);
        System.out.println("订单"+repayment);
        //生成订单
        repayment.setRDate(new Date());
        //待还款金额
        repayment.setSurplusMoney(repayment.getSurplusMoney()-repayment.getRMoney());
        //已还期数
        repayment.setAlreadyMonth(repayment.getAlreadyMonth()+1);
        //待还期数
        repayment.setResidueMoney(repayment.getResidueMoney()-1);
        //还清了订单状态改为已还清
        if(repayment.getSurplusMoney()==0||repayment.getResidueMoney()==0){
            LoanApplication loanApplication = new LoanApplication();
            loanApplication.setLId(repayment.getLId());
            loanApplication.setOrderState(Constant.LOAN_ORDER_STATE_EMPTY);
            loanApplicationService.update(loanApplication);
        }
        //提前还款把redis的键删除
        redisUtil.del("loan:"+repayment.getLId()+","+repayment.getAlreadyMonth());
        //增加支付分
        user.setCredit((int)((user.getCredit())+repayment.getRMoney()/100));
        userService.update(user);
        repaymentService.insert(repayment);

        //增加资金记录
        Fund fund = new Fund();
        fund.setUId(userId);
        fund.setFundAmunt(repayment.getRMoney());
        fund.setFundPost(MoneyFund.FUND_REPAYMENT);
        fundService.insert(fund);

        //已经逾期了的数据改为已还
        zeroService.LatePayment(Constant.DUE_RETURN,repayment.getLId(),repayment.getAlreadyMonth());
        return "0";
    }


    public void loanData(LoanVo loanVo){
        //还款金额
        if (loanVo.getR_money()==0){
            if(loanVo.getMonth_money()!=0){
                loanVo.setR_money(loanVo.getMonth_money());
            }
            //剩余待还款金额
            if(loanVo.getSurplus_money()==null){
                //未审核时,放款金额为空
                if(loanVo.getMax_money()==null){
                    loanVo.setMax_money((int) loanVo.getL_money());
                }
                loanVo.setSurplus_money(Float.valueOf(loanVo.getMax_money()));
            }
        }
        //已还期数
        if(loanVo.getAlready_month()==null){
            loanVo.setAlready_month(0);
        }
        //待还期数
        // 剩余还款期数
        if(loanVo.getResidue_money()==null){
            loanVo.setResidue_money(loanVo.getL_month());
            if(loanVo.getResidue_money()==null){
                loanVo.setResidue_money(0);
            }
        }
        //待还金额
        loanVo.setSurplus_money(loanVo.getR_money()*loanVo.getResidue_money());
    }
}
